export default {
  props: {
    type: {
      type:String,
      default:"add"
    },
    id: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      loading: false,
      http: null,
      form: {},
      rules: {},
      formApiConfig: { //form 接口配置
        add: "",
        detail: "",
        edit: ""
      }
    }
  },
  computed: {
    disabled() {
      return this.type == "detail";
    },
  },
  mounted() {
    this.handleHttp()
  },
  methods: {
    /**
     *
     *处理接口地址
     */
    handleHttp() {
      if (this.type == "add") {
        this.http = this.formApiConfig['add'];
      } else {
        this.getDetail();
        this.http = this.formApiConfig['edit'];
      }
    },
    /**
     *
     *获取表单详情
     */
    getDetail() {
      return new Promise((reslove, reject) => {
        this.loading = true
        this.formApiConfig.detail(this.id).then((res) => {
          reslove(res)
          this.loading = false
          if (res.data.code === 0) {
            this.form = res.data.data;
          }else{
            this.$message.error(res.data.msg);
          }
        }).catch(e=>{
          this.loading = false
          reject()
        });
      })
    },
    /**
     *
     * 处理提交
     * @param {*} formName 表单名称
     */
    submit(formName = 'form') {
      this.form.ID = this.id;
      this.handleSubmit(formName).then(res => {
        return new Promise((reslove, reject) => {
          this.loading = true;
          this.http(this.form).then((res) => {
            this.loading = false;
            if (res.data.code == 0) {
              this.$message.success(res.data.msg);
              this.success()
            } else {
              this.$message.error(res.data.msg);
            }
            reslove(res)
          }).catch((error) => {
            reject()
            this.$message.error('请求失败');
            this.loading = false;
            this.close();
          });
        })
      })
    },
    /**
     * 提交表单数据
     * @param callback 回调函数
     * @param formName 表单名称
     */
    handleSubmit( formName = 'form') {
      return new Promise((reslove, reject) => {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            reslove()
          } else {
            reject()
          }
        })
      })
    },
    /**
     *重置表单
     * @param {string} [formName='form']
     */
    resetForm(formName = 'form') {
      this.$refs[formName].resetFields();
    },
    /**
     * 向父组件提交关闭事件
     */
    close() {
      this.$emit('close');
    },
    /**
     * 向父组件提交提交成功事件
     */
    success() {
      this.$emit('success');
      this.close()
    }
  }
}